package com.tenny.mystory;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;

public class TextViewVertical extends View {

    public static final int START_LEFT = 1;
    public static final int START_RIGHT = 2;

    public static final int NONE = 0;



    @IntDef({START_LEFT, START_RIGHT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface START_ORIENTATION {
    }

    private float textSize = 56;
    private int textColor = Color.BLACK;
    private String text = "";
    private int startOrientation = START_LEFT;
    private float textHorizontalMargin = dip2px(getContext(), 4);
    private float textVerticalMargin = dip2px(getContext(), 3);

    Paint paint;
    int width;
    int height = -1;
    /**
     * 全部文字内容 用以view初始化时候 计算总宽度
     */
    private String totalText;

    public TextViewVertical(Context context) {
        super(context);
        init();
    }

    public TextViewVertical(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TextViewVertical);
        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; i++) {
            int index = typedArray.getIndex(i);
            if (index == R.styleable.TextViewVertical_v_start) {
                startOrientation = typedArray.getInt(index, START_LEFT);
            } else if (index == R.styleable.TextViewVertical_v_text) {
                text = typedArray.getString(index);
            } else if (index == R.styleable.TextViewVertical_v_textColor) {
                textColor = typedArray.getColor(index, Color.BLACK);
            } else if (index == R.styleable.TextViewVertical_v_textSize) {
                textSize = typedArray.getDimension(index, 16);
            } else if (index == R.styleable.TextViewVertical_v_textVerticalMargin) {
                textVerticalMargin = typedArray.getDimension(index, textVerticalMargin);
            } else if (index == R.styleable.TextViewVertical_v_textHorizontalMargin) {
                textHorizontalMargin = typedArray.getDimension(index, textHorizontalMargin);
            }
        }
        typedArray.recycle();
        init();
    }

    private void init() {
        paint = new Paint();
        if (textSize > 0) {
            paint.setTextSize(textSize);
        }
        paint.setColor(textColor);
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int h = measureHeight(heightMeasureSpec);
        //此处修复relativelayout下存在的异常
        if (height == -1) {
            height = h;
        } else {
            if (height > h) {
                height = h;
            }
        }
        width = measureWidth(widthMeasureSpec);
        if(width<getMinimumWidth()){
            width=getMinimumWidth();
        }
        if(width<getTotalTextWidth()){
            width= (int) getTotalTextWidth();
        }

        setMeasuredDimension(width, height);
    }

    /**
     * 设置字体
     * @param typeface
     */
    public void setTypeface(Typeface typeface) {
        paint.setTypeface(typeface);
        invalidate();
    }

    public void setTextHorizontalMargin(float textHorizontalMargin) {
        this.textHorizontalMargin = textHorizontalMargin;
        invalidate();
    }

    public void setTextVerticalMargin(float textVerticalMargin) {
        this.textVerticalMargin = textVerticalMargin;
        invalidate();
    }

    /**
     * 设置文字尺寸
     *
     * @param textSize
     */
    public void setTextSize(float textSize) {
        this.textSize = textSize;
        invalidate();
    }

    /**
     * 设置文字颜色
     *
     * @param textColor
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
        invalidate();
    }

    /**
     * 设置文字
     *
     * @param text
     */
    public void setText(String text) {
        this.text = text;
        requestLayout();
        invalidate();
    }
    public String  getText(){
        return this.text;
    }
    /**
     * 设置文字起始方向
     *
     * @param startOrientation
     */
    public void setStart(@START_ORIENTATION int startOrientation) {
        this.startOrientation = startOrientation;
        invalidate();
    }


    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {

            result = specSize;
        } else {
            return (int) measureTextWidth();
        }
        return result;
    }

    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = (int) (getOneWordHeight() * text.length());
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private float measureTextWidth() {
        int colNum = getColNumOfText(text);
        if (colNum == 1) {
            return getOneWordWidth() + getPaddingLeft() + getPaddingRight();
        }

        return getOneWordWidth() * colNum + getPaddingLeft() + getPaddingRight();
    }

    private float getTextBaseLine(RectF rect) {
        Paint.FontMetricsInt metricsInt = paint.getFontMetricsInt();
        return (rect.top + rect.bottom - metricsInt.top - metricsInt.bottom) / 2;
    }


    private int getColNumOfText(String text) {

        int oneRowWordCount = getColWordCount();
        int colNum = text.length() / oneRowWordCount;
        if (text.length() % oneRowWordCount > 0) {
            colNum++;
        }
        return colNum;
    }



    public float getOneWordWidth() {
        float oneWorkWidth= paint.measureText(getResources().getString(R.string.word)) + textHorizontalMargin;
        return oneWorkWidth;
    }

    private float getOneWordHeight() {
       /* Paint.FontMetricsInt metricsInt = paint.getFontMetricsInt();
        return (metricsInt.bottom - metricsInt.top);*/
        Rect rect = new Rect();
        paint.getTextBounds(getResources().getString(R.string.word), 0, 1, rect);
        return rect.height() + textVerticalMargin;
    }


    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int oneLineWordCount = getColWordCount();

        float w = getOneWordWidth();
        float h = getOneWordHeight();

        int colNum = getColNumOfText(text);

        int currentCol = 0;
        for (int i = 0; i < text.length(); i++) {
            String str = String.valueOf(text.charAt(i));
            int currentRow = i % oneLineWordCount;
            if (colNum == 1) {
                currentRow = i;
            }
            if (colNum > 1) {
                currentCol = (i) / oneLineWordCount;
            }
            drawText(w, h, currentCol, currentRow, str, canvas);
        }
    }

    /**
     *
     * @param w
     * @param h
     * @param currentCol 文字当前行数
     * @param currentRow 文字当前列数
     * @param str
     * @param canvas
     */
    private void drawText(float w, float h, int currentCol, int currentRow, String str, Canvas canvas) {
        RectF rectF;
        if (startOrientation == START_LEFT) {
            rectF = new RectF(currentCol * w, currentRow * h, currentCol * w + w, currentRow * h + h);
        } else {
            rectF = new RectF((width - (currentCol + 1) * w), currentRow * h, (width - (currentCol + 1) * w) + w, currentRow * h + h);
        }
        float baseline = getTextBaseLine(rectF);
        paint.setColor(textColor);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawText(str, rectF.centerX(), baseline, paint);
    }

    public void setTotalText(String totalText) {
        this.totalText = totalText;
    }

    private float getTotalTextWidth(){
        if(!TextUtils.isEmpty(totalText)){
            int colNum=getColNumOfText(totalText);
            if (colNum == 1) {
                return getOneWordWidth() + getPaddingLeft() + getPaddingRight();
            }
            return getOneWordWidth() * colNum + getPaddingLeft() + getPaddingRight();
        }
        return 0;
    }

    /**
     * 总列数
     * @return
     */
    public int getTotalCol(){
        if(!TextUtils.isEmpty(totalText)){
            return getColNumOfText(totalText);
        }
        return 0;
    }

    /**
     * 一列多少个字
     * @return
     */
    public int getColWordCount() {
        int oneLineWordCount = (int) (height / getOneWordHeight());
        return oneLineWordCount;
    }
    /**
     * 一屏显示多少列
     */
    public int getColNumOfScreen(){
        int colNumOfScreen=0;
        if(getOneWordWidth()!=0){
            colNumOfScreen= (int) (getMinimumWidth()/getOneWordWidth());
        }
        return colNumOfScreen;
    }
}